package controllers

import (
	"commerce/common"
	"commerce/data"
	"commerce/model"
	"commerce/utils"
	"html/template"
	"net/http"
	"path/filepath"
	"strconv"
	"strings"
)

func init() {

	common.Templates["category"] = template.Must(template.ParseFiles(filepath.Join(common.CurDir, "views/templates/category.html")))
	common.Templates["edit"] = template.Must(template.ParseFiles(filepath.Join(common.CurDir, "views/templates/category_edit.html")))
}

func ListCategory(w http.ResponseWriter, r *http.Request) {

	pageNo, err := strconv.Atoi(r.FormValue("pageNo"))
	if err != nil {
		pageNo = 1
	}
	pageSize, err := strconv.Atoi(r.FormValue("pageSize"))
	if err != nil {
		pageSize = common.PAGE_SIZE
	}

	name := strings.TrimSpace(r.FormValue("name"))

	var page, _ = data.PageCategory(pageNo, pageSize, name)

	if page == nil {
		common.Templates["5xx"].Execute(w, nil)
		return
	}
	// 分页条件查询使用
	var qs = r.URL.RawQuery

	index := strings.Index(r.RequestURI, "&pageNo=")
	var flag bool
	// 这一步操作是点击分页来的
	if index != -1 {
		qs = r.RequestURI[:index]
		flag = true
	} else {
		// 首次点击搜索按钮查询
		flag = false
		qs = "?"
		if len(name) > 0 {
			qs += "name=" + name
		}
	}
	if flag {
		page.Url = qs
	} else {
		page.Url = r.RequestURI + qs
	}

	common.Templates["category"].Execute(w, page)
}

func AddUIHandler(w http.ResponseWriter, r *http.Request) {

	list, _ := data.ListParentCategory()
	c := model.Category{ParentCategories: list}

	common.Templates["edit"].Execute(w, c)
}

func GetCategoryHandler(w http.ResponseWriter, r *http.Request) {

	id, err := strconv.Atoi(r.FormValue("id"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	c, err := data.GetCategoryById(id)
	if err != nil {
		common.Templates["5xx"].Execute(w, err.Error())
		//http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	list, _ := data.ListParentCategory()
	c.ParentCategories = list
	common.Templates["edit"].Execute(w, c)
}

func AddOrEditCategoryHandler(w http.ResponseWriter, r *http.Request) {

	var id = 0
	idVal := r.PostFormValue("id")
	if len(idVal) > 0 {
		id, _ = strconv.Atoi(idVal)
	}
	categoryName := r.PostFormValue("categoryName")
	description := r.PostFormValue("description")
	priority, _ := strconv.Atoi(r.PostFormValue("priority"))
	parent, _ := strconv.Atoi(r.PostFormValue("parent"))
	var mainImg = ""
	f, header, err := r.FormFile("mainImg")

	// 如果用户上传了图片
	if err == nil && f != nil {
		// 先上传新图片
		uploadedPath, err := utils.Upload(f, header.Filename)
		if err != nil {
			common.Error.Printf("upload category main img failed, filename:%s, err:%v", header.Filename, err)
		} else {
			mainImg = uploadedPath
			// 更新操作
			if id > 0 {
				// 删除老的图片(如果有)
				cp, _ := data.GetCategoryById(id)
				if cp != nil && len(cp.MainImg) > 0 {
					fns := strings.LastIndex(cp.MainImg, "/")
					if fns > -1 {
						utils.Delete(cp.MainImg[fns+1:])
					}
				}
			}
		}
	}
	c := model.Category{Id: id, Parent: parent, Name: categoryName, Description: description, Priority: priority, MainImg: mainImg}
	if id <= 0 {
		id, err = data.AddCategory(c)
	} else {
		id, err = data.UpdateCategory(c)
	}
	//重定向到列表
	http.Redirect(w, r, "/commerce/api/v2/category/list", http.StatusFound)
}

func DeleteCategoryHandler(w http.ResponseWriter, r *http.Request) {

	id, err := strconv.Atoi(r.FormValue("id"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	data.UpdateCategoryStatus(id, 0)

	//重定向到列表
	http.Redirect(w, r, "/commerce/api/v2/category/list", http.StatusFound)
}

func UpdateCategoryStatusHandler(w http.ResponseWriter, r *http.Request) {

	id, err := strconv.Atoi(r.FormValue("id"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	data.UpdateCategoryStatus(id, 1)

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
}
